package com.hospital.hms.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import com.hospital.hms.common.CommonResult;
import com.hospital.hms.controller.form.InsertWorkPlanForm;
import com.hospital.hms.controller.form.SelectDoctorWorkPlanInTime;
import com.hospital.hms.service.DoctorWorkPlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/doctor/work/plan")
@Tag(name = "DoctorWorkPlanController", description = "门诊管理接口")
@CrossOrigin(origins = "http://localhost:4000", allowCredentials = "true")
public class DoctorWorkPlanController {
    @Autowired
    DoctorWorkPlanService doctorWorkPlanService;

    @PostMapping("/selectWorkPlanByTime")
    @SaCheckLogin
    @Operation(summary = "出诊计划查询")
    public CommonResult selectWorkPlanByTime(@RequestBody @Valid SelectDoctorWorkPlanInTime form) {
        Map param = BeanUtil.beanToMap(form);
    /**
     *  因为前端要显示连续日期：
     * 根据开始和结束日期，生成连续的日期
     *在这段代码中使用DateField.DAY_OF_MONTH的目的是指定日期范围的迭代单位。具体来说，当你创建一个日期范围并希望逐日遍历时，
     * DateField.DAY_OF_MONTH告诉DateUtil.range方法，你希望按照每月的天来递增。这样，无论开始日期和结束日期之间相隔多少天，
     * range方法都会生成一个连续的日期列表，每个日期都是按照月中的天数逐一递增的。
     * */
        DateRange range = DateUtil.range(new DateTime(form.getStartDate()),
                new DateTime(form.getEndDate()), DateField.DAY_OF_MONTH);
        ArrayList dateList = new ArrayList<>();
//        将连续的日期保存到集合中
        range.forEach(one -> {
            dateList.add(one.toDateStr());
        });
//        传递给selectWorkPlanByTime
        JSONArray array = doctorWorkPlanService.selectWorkPlanByTime(param, dateList);
//        清空dateList数据格式
        dateList.clear();

//        王dateList放入格式化的日期，前端用作表头展示
        DateRange range2 = DateUtil.range(new DateTime(form.getStartDate()),
                new DateTime(form.getEndDate()), DateField.DAY_OF_MONTH);
        range2.forEach(one -> {
            dateList.add(one.toString("MM月dd日") + "(" + one.dayOfWeekEnum().toChinese() + ")");
        });
        return CommonResult.ok().put("result", array).put("dateList", dateList);
    }

    @PostMapping("/insert")
    @SaCheckLogin
    @Operation(summary = "添加门诊日程")
    public CommonResult insert(@RequestBody @Valid InsertWorkPlanForm form) {
        Map param = BeanUtil.beanToMap(form);
        String result = doctorWorkPlanService.insert(param);
        return CommonResult.ok().put("result", result);
    }
}
